<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>前后端分离开发</title>
    <!-- 引入axios库 -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
姓名：<input type="text" id="add-student-name">
年龄：<input type="text" id="add-student-age">
性别：<input type="text" id="add-student-gender">
<button id="addStudent">添加学生</button>
<hr>

查询id：<input type="text" id="get-student-id">
<button id="getStudentById">查询学生</button>
<hr>

<button id="getStudents">获取所有学生</button>
<hr>
<p id="result"></p>

<script>
    // 点击添加学生按钮
    document.getElementById("addStudent").addEventListener("click", function () {
        // 模拟要添加的学生数据，替换成你自己的信息
        const data = {
            "name": document.getElementById("add-student-name").value,
            "age": document.getElementById("add-student-age").value,
            "gender": document.getElementById("add-student-gender").value
        }
        axios.post('http://localhost:5000/students', data)
            .then(function (response) {
                // 得到的response中的data是js对象，转换成字符串显示
                document.getElementById('result').innerText = JSON.stringify(response.data);
            })
            .catch(function (error) {
                console.log(error);
            });
    });
    // 点击查询学生按钮
    document.getElementById("getStudentById").addEventListener("click", function () {
        const id = document.getElementById("get-student-id");
        axios.get('http://localhost:5000/students/' + id)
            .then(function (response) {
                document.getElementById('result').innerText = JSON.stringify(response.data);
            })
            .catch(function (error) {
                console.log(error);
            });
    });
    // 点击获取所有学生按钮
    document.getElementById("getStudents").addEventListener("click", function () {
        axios.get('http://localhost:5000/students')
            .then(function (response) {
                document.getElementById('result').innerText = JSON.stringify(response.data);
            })
            .catch(function (error) {
                console.log(error);
            });
    });
</script>
</body>
</html>